package cn.com.ourclass.webviewnew.wb.tools;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.hc.framework.engine.util.HttpCallBack;
import com.hc.framework.engine.util.HttpUtils;
import com.lidong.photopicker.PhotoPickerActivity;
import com.lidong.photopicker.PhotoPreviewActivity;
import com.lidong.photopicker.SelectModel;
import com.lidong.photopicker.intent.PhotoPickerIntent;
import com.lidong.photopicker.intent.PhotoPreviewIntent;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import cn.com.ourclass.webviewnew.R;


/**
 * Created by HuHaiqin on 2017/11/21.
 */

public class PhotoSelectActivity extends AppCompatActivity {

    private Context mContext = this;
    private static final int REQUEST_CAMERA_CODE = 10;
    private static final int REQUEST_PREVIEW_CODE = 20;
    public static final int REQUEST_PHOTO_CODE = 30;

    private ArrayList<String> imagePaths = new ArrayList<>();
    private ArrayList<String> images = new ArrayList<>();

    private GridView gridView;
    private GridAdapter gridAdapter;

    private Button btn;

    AlertDialog.Builder builder;


    public static PhotoSelectActivity instance = null;


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(instance != null) {
            PhotoSelectActivity.instance.finish();
        }

        setContentView(R.layout.activity_photo_select);
        instance = this;

        if (ActivityCompat.checkSelfPermission(PhotoSelectActivity.this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            // 权限未被授予
            GetPermissionUtils.requestCameraPermission(PhotoSelectActivity.this);
        }else{
            if (ActivityCompat.checkSelfPermission(PhotoSelectActivity.this, Manifest.permission.RECORD_AUDIO)!= PackageManager.PERMISSION_GRANTED) {
                GetPermissionUtils.requestMarkPermission(PhotoSelectActivity.this);
            }else{
                //
            }

        }

        TextView title = (TextView)findViewById(R.id.title);
        title.setText("上传照片");

        LinearLayout mInage=(LinearLayout)findViewById(R.id.back) ;
        mInage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        gridView = (GridView)findViewById(R.id.gridView);
        btn = (Button)findViewById(R.id.btn);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                upload();
            }
        });

        initGrid();
    }

    private void initGrid(){
        int cols = getResources().getDisplayMetrics().widthPixels / getResources().getDisplayMetrics().densityDpi;
        cols = cols < 5 ? 5 : cols;
        gridView.setNumColumns(cols);

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String imgs = (String) parent.getItemAtPosition(position);
                images = imagePaths;
                images.remove("paizhao");
                if ("paizhao".equals(imgs) ){
                    PhotoPickerIntent intent = new PhotoPickerIntent(PhotoSelectActivity.this);
                    intent.setSelectModel(SelectModel.MULTI);
                    intent.setShowCarema(true); // 是否显示拍照
                    intent.setMaxTotal(9); // 最多选择照片数量，默认为6
                    intent.setSelectedPaths(images); // 已选中的照片地址， 用于回显选中状态
                    startActivityForResult(intent, REQUEST_CAMERA_CODE);
                }else{
                    PhotoPreviewIntent intent = new PhotoPreviewIntent(PhotoSelectActivity.this);
                    intent.setCurrentItem(position);
                    intent.setPhotoPaths(images);
                    startActivityForResult(intent, REQUEST_PREVIEW_CODE);
                }
            }
        });
        loadAdpater(imagePaths);


    }

    private void loadAdpater(ArrayList<String> paths){
        if (imagePaths!=null&& imagePaths.size()>0){
            imagePaths = new ArrayList<>();
        }
        if(paths.size() == 0){
            //paths.add("paizhao");
            imagePaths.add("paizhao");
        }else{
            if(!paths.get(paths.size()-1).equals("paizhao")){
                paths.add("paizhao");
            }
            imagePaths.addAll(paths);
        }

        EditModel.imagePaths = imagePaths; //存储一下
        gridAdapter  = new GridAdapter(imagePaths);
        gridView.setAdapter(gridAdapter);
        try{
            JSONArray obj = new JSONArray(imagePaths);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(resultCode == RESULT_OK) {
            switch (requestCode) {
                // 选择照片
                case REQUEST_CAMERA_CODE:
                    ArrayList<String> list = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);
                    if(list.size() == 0){
                        list.add("paizhao");
                    }
                    loadAdpater(list);
                    break;
                // 预览
                case REQUEST_PREVIEW_CODE:
                    ArrayList<String> ListExtra = data.getStringArrayListExtra(PhotoPreviewActivity.EXTRA_RESULT);
                    loadAdpater(ListExtra);
                    break;
            }
        }

    }

    private class GridAdapter extends BaseAdapter {
        private ArrayList<String> listUrls;
        private LayoutInflater inflater;
        public GridAdapter(ArrayList<String> listUrls) {
            this.listUrls = listUrls;
            if(listUrls.size() == 7){
                listUrls.remove(listUrls.size()-1);
            }
            inflater = LayoutInflater.from(PhotoSelectActivity.this);
        }

        public int getCount(){
            return  listUrls.size();
        }
        @Override
        public String getItem(int position) {
            return listUrls.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = inflater.inflate(R.layout.item_photo_select, parent,false);
                holder.image = (ImageView) convertView.findViewById(R.id.imageView);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder)convertView.getTag();
            }

            final String path=listUrls.get(position);
            if (path.equals("paizhao")){
                holder.image.setImageResource(R.mipmap.find_add_img);
            }else {
                Glide.with(PhotoSelectActivity.this)
                        .load(path)
                        //.placeholder(R.mipmap.default_error)
                        //.error(R.mipmap.default_error)
                        .centerCrop()
                        .crossFade()
                        .into(holder.image);
            }
            return convertView;
        }
        class ViewHolder {
            ImageView image;
        }
    }

    boolean stopThread = false;
    ArrayList<String> resultImagePath = new ArrayList<>(); //最终上传的图片地址
    ArrayList<String> uploadPaths;
    int uploadLength; //待上传的文件个数
    ProgressDialog pDialog; //进度条对话框
    String resultUrls = "";

    /**
     * 上传图片到七牛云
     */
    public void uploadPic(final ArrayList<String> imgs){
        final ProgressDialog dialog = ProgressDialog.show(this, "提示", "正在上传..");
        HttpUtils httpUtils = new HttpUtils();
        Map<String, String> params = new HashMap<>();

        httpUtils.post(params, getResources().getString(R.string.uptoken),
                new HttpCallBack<UpTokenModel>() {

                    @Override
                    public void onError() {
                        Toast.makeText(PhotoSelectActivity.this,"获取失败",Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onSuccess(UpTokenModel result) {

                        for(int i=0;i<imgs.size();i++){
                            String key= Uploadfile.Uploadpic(BitmapFactory.decodeFile(imgs.get(i)),result.getUptoken());
                            String newurl ="http://img.56class.cn/"+key;
                            if(i+1 != imgs.size()  ){
                                resultUrls += newurl+",";
                            }else{
                                resultUrls += newurl;
                            }
                        }
                        dialog.dismiss();
                        Intent intent = new Intent();
                        intent.putExtra("result", resultUrls);
                        setResult(RESULT_OK, intent);
                        finish(); //结束当前的activity的生命周期
                    }
                });
    }


    private void upload(){

        uploadPaths = new ArrayList<>();
        uploadLength = 0;
        for(int i = 0 ; i < imagePaths.size()-1 ; i++){
            String path = imagePaths.get(i);
            //uploadQiniu(path);
            uploadPaths.add(path);
        }

        uploadLength = uploadPaths.size();
        if(uploadPaths.size()==0){
            Toast.makeText(this,"图片不能为空",Toast.LENGTH_LONG).show();
        }else{
            uploadPic(uploadPaths);
        }
    }

    private void uploadEnd(){
        Log.e("hhq",resultImagePath.toString());
    }

}
